package com.newenergy.wisehome;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;

import com.newenergy.light.Helper.BleDataHelper;
import com.newenergy.light.ble.AdvertiserManager;
import com.newenergy.wisehome.common.MyEvent;
import com.newenergy.wisehome.common.helper.LogHelper;
import com.newenergy.wisehome.common.helper.SPUtil;
import com.newenergy.wisehome.common.helper.ToastUtil;
import com.newenergy.wisehome.common.util.LocaleUtil;
import com.newenergy.wisehome.common.util.NotifyHelper;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.config.Constants;
import com.newenergy.wisehome.data.bean.BallLight;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.bean.FamilyUnique;
import com.newenergy.wisehome.data.ormlite.dao.BallLightDao;
import com.newenergy.wisehome.data.ormlite.dao.DeviceCategoryDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyUniqueDao;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.services.BDService;
import com.newenergy.wisehome.ui.activity.BaseActivity;
import com.newenergy.wisehome.ui.fragment.MainFragment;
import com.newenergy.wisehome.ui.fragment.WelcomeFragment;
import com.newenergy.wisehome.ui.widget.CustomDialog;
import com.newenergy.wisehome.update.CheckVersionInfoTask;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

public class MainActivity extends BaseActivity {

    private static String TAG = "LFX";
    public boolean isPermission;
    private File mApkFile;
    PowerManager powerManager = null;
    PowerManager.WakeLock wakeLock = null;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void ininListen() {

    }

    @Override
    protected void init() {
        super.init();

        BLLocalFamilyManager.getInstance().withActivity(this);
        boolean bool = SPUtil.getBool(Constants.NEVERREMIND, false);

        if (bool) {
            if (findFragment(MainFragment.class) == null) {
                loadRootFragment(R.id.main_container, MainFragment.newInstance());  //load root Fragment
            }
        }else {
            if (findFragment(WelcomeFragment.class) == null) {
                loadRootFragment(R.id.main_container, WelcomeFragment.newInstance());  //load root Fragment
            }
        }

        showNotify();

        boolean isDownload = SPUtil.getBool(Constants.ISDOWNLOAD, false);
        if (!isDownload){
            new CheckVersionInfoTask(MainActivity.this, true).execute();
        }else {
            ToastUtil.toast(getString(R.string.is_being_updated));
        }

        powerManager = (PowerManager)this.getSystemService(this.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1000) {
            String qrStr = data.getExtras().getString("result");
            LogHelper.i("qrStr=" + qrStr);
            decodeQRContent(qrStr);
            return;
        }

        switch (requestCode) {
            case 10086:
                installProcess(mApkFile);

                break;
        }

    }


    private void decodeQRContent(String qrStr) {
        if (!qrStr.contains("[")) return;
        String[] strs1 = qrStr.split("\\[");
        if (strs1.length != 3 || TextUtils.isEmpty(strs1[0])) return;
        //解析家庭

        String[] familyStrs = strs1[1].split("&");
        int length = familyStrs.length;
        if (length<7){
            toast("二维码数据有误,请检查APP是否是最新版本");
            return;
        }

        FamilyUniqueDao uniqueDao = new FamilyUniqueDao(this);

        FamilyDao mFamilyDao = new FamilyDao(this);
        DeviceCategoryDao mDeviceCategoryDao = new DeviceCategoryDao(this);


        String familyId = familyStrs[0];
        String familyName = familyStrs[1];
        int seed = Integer.parseInt(familyStrs[2],16);
        int feedback = Integer.parseInt(familyStrs[3],16);
        int ballLightCount = Integer.parseInt(familyStrs[4]);
        int deviceCount = Integer.parseInt(familyStrs[5]);
        String blFamilyId = familyStrs[6];


        if (familyId.equals("12345678")) {
            showTipDialog(getString(R.string.no_support_default));
            mHandler.sendEmptyMessageDelayed(1, 1000);
            return;
        }


        //根据家庭码查找家庭中是否有存在家庭
        Family familyById = mFamilyDao.getById(familyId);
        FamilyUnique unique = uniqueDao.getByFamily(familyId);
        if (familyById != null&&unique!=null) {
            return;
        }

        Family family = new Family(familyId,familyName,ballLightCount,deviceCount,seed,feedback);
        family.setType(0);
        family.setBlFamilyId(blFamilyId);
        List<FamilyUnique> familyUniques = uniqueDao.getAll();
        for (FamilyUnique familyUnique:familyUniques ) {//主机创建的家庭删除之后，从分享那里获得的家庭设置为可操作状态。
            if (familyId.equals(familyUnique.getFamilyId())){
                family.setType(1);
            }
        }

        SPUtil.put("FAMILY_ID", familyId);
        String name = family.getName();

        List<Family> familiys = mFamilyDao.getAll();
        //存放family的名字的集合
        List<String> familyNames = new ArrayList<>();

        for (Family family1 : familiys) {
            if (!familyId.equals(family1.getFamilyId())) {
                familyNames.add(family1.getName());
            }
        }


        for (Family tem :familiys) {
            if (name.equals(tem.getName())&&!familyId.equals(tem.getFamilyId())){
                name = getNewName(name, familyNames);
                family.setName(name);
            }
        }


        if (familyById == null) {
            mFamilyDao.add(family);
        } else {
            familyById.setBallLightCount(ballLightCount);
            familyById.setDeviceCount(deviceCount);
            familyById.setName(name);
            mFamilyDao.updateFamily(familyById);

        }

        BallLight allLight =new BallLight(familyId,1,"00",getString(R.string.all_device),"suo you she bei","bg_all_device_n");
        AppManager.getInstance(this).mAllGroup = allLight;

        AppManager.getInstance(this).mCurrFamily=family;
        AppManager.getInstance(this).mGroupIndex = 0;
        AppManager.getInstance(this).mHEAIndex = 0;
        AdvertiserManager.getInstance().mSeed = family.getSeed();
        AdvertiserManager.getInstance().mFeedBack = family.getFeedback();
        List<DeviceCategory> familyDeviceCategorys = mDeviceCategoryDao.getFamilyDeviceCategorys(familyId);


        BLLocalFamilyManager blFamilyManager = BLLocalFamilyManager.getInstance();

        //分享过来的有就覆盖，没有就添加
        if (strs1[0].equals("7201")) {
            //解析球泡灯
            isShowAllLight = true;
            BallLightDao mBallLightDao = new BallLightDao(this);


            String[] groupStrs = strs1[2].split("#");
            for (String groupStr : groupStrs) {
                String[] gStrs = groupStr.split("&");

                String gid = gStrs[0];
                String gname = gStrs[1];
                String pinyinString = "";
                BallLight hadBallLight = mBallLightDao.getFamilyBallLight(familyId, gid);
                DeviceCategory hadDeviceCategory = mDeviceCategoryDao.getFamilyBallLightByGroupId(familyId, gid);
                //存放deviceCategory名字的集合
                List<String> deviceCategoryName = new ArrayList<>();

                for (DeviceCategory deviceCategory : familyDeviceCategorys) {
                    if (!gid.equals(deviceCategory.getGroupId())) {
                        deviceCategoryName.add(deviceCategory.getName());
                    }
                }


                gname = getNewName(gname, deviceCategoryName);
                if (hadBallLight == null) {
                    String icName = "btn_balllight";
                    BallLight ballLight = new BallLight(familyId, 1, gid, gname, pinyinString, icName);
                    mBallLightDao.add(ballLight);
                    DeviceCategory deviceCategory = ballLight.covertToDeviceCategory();
                    mDeviceCategoryDao.add(deviceCategory);
                }else {
                    //当数据库中已经有相同家庭码跟组号的时候
                    hadBallLight.setName(gname);
                    mBallLightDao.updateBallLight(hadBallLight);
                    if (hadDeviceCategory != null) {
                        hadDeviceCategory.setName(gname);
                        mDeviceCategoryDao.updateDeviceCategory(hadDeviceCategory);
                    }
                }
            }

        } else if (strs1[0].equals("7202")) {
            //解析小家电
            isShowAllLight = false;
            String[] groupStrs = strs1[2].split("#");
            for (String groupStr : groupStrs) {
                String[] gStrs = groupStr.split("&");

                String gid = gStrs[0];
                String gname = gStrs[1];
                int category = Integer.parseInt(gStrs[2]);
                String deviceId = gStrs[3];
                String model = BleDataHelper.subHexStr(deviceId, 0, 4);
                DeviceCategory familyHEAByDeviceid = mDeviceCategoryDao.getFamilyHEAByDeviceid(familyId, deviceId);
                //存放deviceCategory名字的集合
                List<String> deviceCategoryName = new ArrayList<>();
                for (DeviceCategory deviceCategory : familyDeviceCategorys) {
                    if (!gid.equals(deviceCategory.getGroupId())) {
                        deviceCategoryName.add(deviceCategory.getName());
                    }
                }
                gname = getNewName(gname, deviceCategoryName);

                if (familyHEAByDeviceid == null) {
                    if (category == 2) {
                        String icName = "btn_fan";
                        DeviceCategory deviceCategory = new DeviceCategory(familyId, 2, gid, gname, icName, deviceId, model);
                        mDeviceCategoryDao.add(deviceCategory);
                    } else if (category == 3) {
                        String icName = "btn_fanlamp";

                        DeviceCategory deviceCategory = new DeviceCategory(familyId, 3, gid, gname, icName, deviceId, model);
                        mDeviceCategoryDao.add(deviceCategory);
                    } else if (category == 4) {
                        String icName = "btn_electricheater";

                        DeviceCategory deviceCategory = new DeviceCategory(familyId, 4, gid, gname, icName, deviceId, model);
                        mDeviceCategoryDao.add(deviceCategory);
                    } else if (category == 5) {
                        String icName = "btn_batnheater";

                        DeviceCategory deviceCategory = new DeviceCategory(familyId, 5, gid, gname, icName, deviceId, model);
                        mDeviceCategoryDao.add(deviceCategory);
                    } else if (category == 6) {
                        String icName = "icon_balcony3";
                        DeviceCategory deviceCategory = new DeviceCategory(familyId, 6, gid, gname, icName, deviceId, model);
                        mDeviceCategoryDao.add(deviceCategory);
                    } else if (category == 7) {
                        String icName = "icon_movie";
                        DeviceCategory deviceCategory = new DeviceCategory(familyId, 7, gid, gname, icName,deviceId , model);
                        mDeviceCategoryDao.add(deviceCategory);
                    } else if (category == 8) {
                        String icName = "icon_music";
                        DeviceCategory deviceCategory = new DeviceCategory(familyId, 8, gid, gname, icName, deviceId, model);
                        mDeviceCategoryDao.add(deviceCategory);
                    } else if (category == 9) {
                        String icName = "btn_healthbasin";
                        DeviceCategory deviceCategory = new DeviceCategory(familyId, 9, gid, gname, icName, deviceId, model);
                        mDeviceCategoryDao.add(deviceCategory);
                    }

                }else {
                    familyHEAByDeviceid.setName(gname);
                    mDeviceCategoryDao.updateDeviceCategory(familyHEAByDeviceid);
                }
            }
        }
        blFamilyManager.updateShareFamilyBLInfo(family);
    }


    //递归判断名字是否相等
 /*   private String getName(String name,String gid ,List<DeviceCategory> familyDeviceCategorys,int temCount) {
        int count = temCount;
        String newName = temCount<1 ? name : name +count ;
        for (DeviceCategory deviceCategory :familyDeviceCategorys) {
            if (deviceCategory.getName().equals(name) && !deviceCategory.getGroupId().equals(gid)) {
                count++;
                getName(name, gid, familyDeviceCategorys, count);
            }
        }
        return newName;
    }
*/


    public String getNewName(String name,List<String> nameList) {
        boolean enable = checkNameEnable(name, nameList);
        if (enable){
            return  name;
        }
        int count = nameList.size() + 1;
        for (int i=1;i<count;i++) {
            String newName = checkNewName(name, i, nameList);
            if (newName != null) {
                return newName;
            }
        }
        return name;
    }

    public boolean checkNameEnable(String name,List<String> nameList){
        if (nameList==null || nameList.size()<1){
            return  true;
        }
        for (String nameIn : nameList) {
            if (name.equals(nameIn)) {
                return false;
            }
        }
        return  true;
    }


    public String checkNewName(String name, int index,List<String> nameList) {
        String newName = name  + index  ;
        for (String nameIn : nameList) {
            if (newName.equals(nameIn)) {
                return null;
            }
        }
        return newName;
    }





    /**
     * 判断是否保存过组
     *
     * @param groups
     * @param gid
     * @return
     */
    public BallLight isSavedGroup(List<BallLight> groups, String gid) {
        for (BallLight group : groups) {
            if (group.getGroupId().equals(gid)) {
                return group;
            }
        }
        return null;
    }

    /**
     * 字符转Int
     *
     * @param str
     * @return
     */
    public int strToInt(String str) {
        int number = -1;
        try {
            number = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return number;
    }


    @Override
    protected void onResume() {
        super.onResume();

        Log.e("LFX", "MainActivity onResume");
        boolean mSpeechEnable= SPUtil.getBool(Constants.SPEECH_ENABLE,false);
        if (mSpeechEnable&& LocaleUtil.getLanguage().startsWith("zh")){
            Intent intent = new Intent(this, BDService.class);
            intent.putExtra("service_cmd","startSpeech");
            startService(intent);
        }
        wakeLock.acquire();

    }



    @Override
    protected void onStart() {
        super.onStart();

    }


    @Override
    protected void onPause() {
        super.onPause();
        Log.e("LFX", "MainActivity onPause");
        boolean mSpeechEnable= SPUtil.getBool(Constants.SPEECH_ENABLE,false);
        if (mSpeechEnable){
            Intent intent = new Intent(this, BDService.class);
            intent.setAction("stop service");
            stopService(intent);

        }
        wakeLock.release();
    }



    @Override
    protected void onStop() {
        super.onStop();

    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("LFX", "onDestroy");
        NotifyHelper.with(this.getApplicationContext(),"2").cancel(10086);
        mHandler.removeCallbacksAndMessages(null);

      /*  RefWatcher refWatcher = BaseApp.getRefWatcher(this);
        refWatcher.watch(this);*/

    }




    public void showNotify() {
        NotifyHelper.with(this.getApplicationContext(),"2")
                .identifier(10086)
                .smallIcon(R.drawable.app)
                .when(System.currentTimeMillis())
                .flags(Notification.FLAG_NO_CLEAR)
                .ongoing(true)
                .title(getString(R.string.app_name))
                .message(getString(R.string.click_into_main))
                .click(MainActivity.class)
                .show();

    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEventBus(MyEvent event){
        switch (event.getTag()){
            case "INSTALL_APK" :
                String apkPath = (String) event.getData();
                mApkFile = new File(apkPath);
                boolean b = mApkFile.isFile();
                if (!b){
                    Log.i(TAG, "handleEventBus: 下载文件错误");
                }else {
                    installProcess(mApkFile);
                }

             return;

        }

    }


    //安装应用的流程
    private void installProcess(File apkFile) {
        boolean haveInstallPermission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先获取是否有安装未知来源应用的权限
            haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {//没有权限
                //请求安装未知应用来源的权限
                 showDialog();
                return;
            }else {
                //有权限，开始安装应用程序
                installApk(apkFile);
                return;
            }
        }
        //有权限，开始安装应用程序
        installApk(apkFile);
    }

    /**
     * 调用系统安装程序安装下载好的apk
     * @param apkFile
     */
    public void installApk(File apkFile) {
        if (apkFile == null) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);

        Uri data ;
        String type = "application/vnd.android.package-archive";
        if (Build.VERSION.SDK_INT>=24){//判读版本是否在7.0以上
            data = FileProvider.getUriForFile(this, "com.newenergy.wisehome.fileprovider", apkFile);//在AndroidManifest中的android:authorities值
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        }else {
            //如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
            try {
                String[] command = {"chmod", "777", apkFile.toString()}; //777代表权限 rwxrwxrwx
                ProcessBuilder builder = new ProcessBuilder(command);
                builder.start();
            } catch (IOException ignored) {
            }
            data = Uri.fromFile(apkFile);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(data, type);
        startActivity(intent);
    }


    public void showDialog(){
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setMessageSize(20);
        builder.setTitle(R.string.tips);
        builder.setMessage(R.string.need_permission_install);
        builder.setPositiveButton(R.string.btn_confirm, (dialog1, which) -> {

            startInstallPermissionSettingActivity();

            dialog1.dismiss();
        });

        builder.setNegativeButton(R.string.btn_cancel,  (dialog12, which) -> dialog12.dismiss());

        CustomDialog customDialog = builder.create();
        customDialog.setCanceledOnTouchOutside(false);
        customDialog.show();
    }


    private void startInstallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);

        startActivityForResult(intent, 10086);
    }


    @Override
    public void onBackPressedSupport() {
        // 对于 4个类别的主Fragment内的回退back逻辑,已经在其onBackPressedSupport里各自处理了
        super.onBackPressedSupport();
    }


    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        // 设置横向(和安卓4.x动画相同)
        return new DefaultHorizontalAnimator();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    dissDialog();
                    break;
            }
        }
    };

}
